package cn.wolfcode.rbac.service.impl;

import cn.wolfcode.rbac.domain.Role;
import cn.wolfcode.rbac.mapper.RoleMapper;
import cn.wolfcode.rbac.query.QueryObject;
import cn.wolfcode.rbac.service.IRoleService;
import cn.wolfcode.rbac.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public void save(Role entity, Long[] ids) {
        roleMapper.insert(entity);

        //维护与权限关系
        if(ids != null){
            for (Long id : ids) {
                roleMapper.insertRelation(entity.getId(), id);
            }
        }

    }

    @Override
    public void update(Role entity, Long[] ids) {
        //先删除关系
        roleMapper.deleteRelation(entity.getId());

        roleMapper.updateByPrimaryKey(entity);

        //维护与权限关系
        if(ids != null){
            for (Long id : ids) {
                roleMapper.insertRelation(entity.getId(), id);
            }
        }
    }

    @Override
    public void delete(Long id) {
        //先删除关系
        roleMapper.deleteRelation(id);
        roleMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Role get(Long id) {
        return roleMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Role> list() {
        return roleMapper.selectAll();
    }

    @Override
    public PageResult query(QueryObject qo) {

        int totalCount =  roleMapper.selectForCount(qo);

        if(totalCount == 0){
            return PageResult.EMPTY_PAGE_RESULT;
        }

        List<Role> list = roleMapper.selectForList(qo);
        return new PageResult(list, totalCount, qo.getCurrentPage(), qo.getPageSize());
    }
}
